<template>
    <div class="home"
        :style="{ '--left-width': leftWidth, '--right-top-height': rightTopHeight, '--menu-back-bround-color': menuBackGroundColor, '--crumbs-height': crumbsHeight }">
        <div class="left">
            <el-scrollbar>
                <el-menu :unique-opened="true" :collapse-transition="false" text-color="rgb(191, 203, 217)"
                    active-text-color="rgb(64, 158, 255)" :background-color="menuBackGroundColor"
                    :default-active="loginInfoStoreData.menuActive" class="el-menu-vertical-demo"
                    :collapse="isCollapse">
                    <template v-for="itm1 in barList" :key="itm1.router">
                        <el-menu-item v-permissionbar="barPermissionFilter(itm1.permission, permissionData.data)"
                            v-if="itm1.child.length == 0" :index="itm1.router" @click="menuClickEv(itm1)">
                            <el-icon v-if="itm1.icon != ''">
                                <component :is="itm1.icon" />
                            </el-icon>
                            <template #title>{{ itm1.title }}</template>
                        </el-menu-item>
                        <el-sub-menu v-permissionbar="barPermissionFilter(itm1.permission, permissionData.data)" v-else
                            :index="itm1.router" :key="itm1.router">
                            <template #title>
                                <el-icon v-if="itm1.icon != ''">
                                    <component :is="itm1.icon" />
                                </el-icon>
                                <span>{{ itm1.title }}</span>
                            </template>
                            <el-menu-item-group v-for="itm2 in itm1.child" :key="itm2.router">
                                <el-menu-item
                                    v-permissionbar="barPermissionFilter(itm2.permission, permissionData.data)"
                                    :index="itm2.router" @click="menuClickEv(itm2)">{{ itm2.title
                                    }}</el-menu-item>
                            </el-menu-item-group>
                        </el-sub-menu>
                    </template>
                </el-menu>
            </el-scrollbar>
        </div>
        <div class="right">
            <div class="top">
                <div class="top1">
                    <div class="top1-content">
                        <el-icon v-if="isCollapse == false" @click="isCollapseEv" size="25">
                            <fold />
                        </el-icon>
                        <el-icon v-else isCollapseEv @click="isCollapseEv" size="25">
                            <expand />
                        </el-icon>
                        <div style="font-weight: bold;font-size: 22px; padding-left: 15px; box-sizing: border-box;">
                            <!-- {{loginInfoStoreData.lessees_name }} -->
                            绍兴艾柯电气有限公司
                        </div>
                    </div>
                    <div style="display: flex;align-items: center;">
                        <div style="padding-right: 5px;"><el-text>欢迎{{ loginInfoStoreData.username }}到来</el-text></div>
                        <div><el-popover placement="top-start" trigger="click">
                                <template #reference>
                                    <el-icon style="cursor:pointer;color: rgb(64, 158, 255);" size="20px">
                                        <user />
                                    </el-icon>
                                </template>
                                <template #default>
                                    <div class="popover-content" @click="updatePasswordShowEv">修改密码</div>
                                    <div class="popover-content" @click="logOutEv">退出登录</div>
                                </template>
                            </el-popover></div>
                    </div>
                </div>
                <el-scrollbar>
                    <div class="top2" v-if="pageWidth > 600">
                        <div class="top2-tabs" @click="tabsItmEv(itm)" v-for="itm in breadcrumbDataList.data"
                            :key="itm.router">
                            <div :class="itm.activate == true ? 'top2-tabs-itm top2-tabs-activate' : 'top2-tabs-itm'">
                                <div style="display: flex; align-items: center;">
                                    <div class="no-select">{{ itm.title }}</div>
                                    <!-- 增加空隙 -->
                                    <div v-if="itm.router != '/home'" style="width: 10px;"></div>
                                    <div v-if="itm.router != '/home'" @click.stop="tabsItmCloseEv(itm)"
                                        class="close-div">
                                        <Close style="width: 8px; 
    height: 8px;" />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-scrollbar>
            </div>
            <div class="bottom" v-loading="loading.loading" :element-loading-text="text"><router-view
                    v-slot="{ Component }">
                    <keep-alive>
                        <component :is="Component" :key="$route.name" v-if="$route.meta.keepAlive" />
                    </keep-alive>
                    <component :is="Component" :key="$route.name" v-if="!$route.meta.keepAlive" />
                </router-view></div>
        </div>
        <!-- 修改密码弹窗 -->
        <el-dialog :draggable="true" v-model="dialogVisible" width="300">
            <div>
                <div class="close-itm"><el-input v-model="passwordObj.oldPassword" style="width: 100%"
                        placeholder="旧密码" />
                </div>
                <div class="close-itm"> <el-input v-model="passwordObj.noewPassword" style="width: 100%"
                        placeholder="新密码" />
                </div>
            </div>
            <template #header>
                <div>修改密码 <span style="color: red;">{{ loginInfoStoreData.username }}</span></div>
            </template>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button @click="updatePasswordEv">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import {
    User,
    Fold,
    Expand,
    Close
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ref, onMounted, onUnmounted, onBeforeUnmount } from 'vue'
import { loginInfoStore, tabsBarStore, loadingStore, permissionStore } from '@/stores/index.js'
import { tabsIsAdd, tabsIsDelete } from '@/utils/tabs.js'
import { barList } from '@/utils/globalConst.js'
import { barPermissionFilter } from '@/utils/barPermission.js'
import { UserLoginPut } from '@/api/setting/users/index.js'
import {  UserLogOutPut } from '@/api/setting/users/index.js'
import { socket, connect } from '@/utils/socketIoService.js'

// 加载状态
const loading = loadingStore()
const { text } = loadingStore()
// const {text} = loadingStore()
const loginInfoStoreData = loginInfoStore()
// 顶部菜单数据
const breadcrumbDataList = tabsBarStore()
// 权限数据
const permissionData = permissionStore()

const route = useRouter()
const isCollapse = ref(false)
const pageWidth = ref(0)
const dialogVisible = ref(false)
const passwordObj = ref({
    oldPassword: '',
    noewPassword: ''
})


let leftWidth = ref('180px')
let rightTopHeight = ref('80px')
let crumbsHeight = ref('35px')
// let menuBackGroundColor = ref('rgb(48, 65, 86)')
let menuBackGroundColor = '#010E1A'

onMounted(async () => {
    sessionStorage.removeItem('online_id')
    // 连接socketio
    connect({
        queryParams: {
            user_id: loginInfoStoreData.user_id,
            lessees_id: loginInfoStoreData.lessees_id,
            token: loginInfoStoreData.token,
            username: loginInfoStoreData.username,
        }
    })
    // 获取页面宽度
    updatePageWidth()
    // 监听获取页面宽度
    window.addEventListener('resize', updatePageWidth);

    // // 监听服务端推送的消息
    // socket.on('loginout', (data) => {
    //     console.log(`Received from server: ${data}`);
    //   })

    socket.on('loginout', onMessage);
})
const onMessage = (message) => {
    // 处理消息...
    console.log('强制下线:', message);
    ElMessageBox.alert('管理员强制下线', '警告', {
    confirmButtonText: '确认',
    callback: () => {
        logOutEv()
    }
  })

  

}
onBeforeUnmount(() => {
    // 移除事件监听器
    socket.off('loginout', onMessage)
    socket.off()
    socket.close()
    console.log('销=======================毁')
});

onUnmounted(() => {
    window.removeEventListener('resize', updatePageWidth);
})



const updatePageWidth = () => {
    pageWidth.value = window.innerWidth
    if (window.innerWidth <= 600) {
        isCollapse.value = true
        leftWidth.value = '50px'
    } else {
        isCollapse.value = false
        leftWidth.value = '180px'
    }
};

// 退出登录
const logOutEv = async () => {
    loginInfoStoreData.token = ''
    loginInfoStoreData.username = ''
    loginInfoStoreData.id = ''
    loginInfoStoreData.menuActive = ''
    breadcrumbDataList.data = [
        {
            router: '/home',
            title: '主页',
            activate: true
        }
    ]

    // await UserLogOutPut({})
    sessionStorage.setItem("logOut", 'true')
    sessionStorage.setItem("token", '')
    sessionStorage.setItem("user_id", null)
    route.push({ path: '/' })
}
// 展开与关闭
const isCollapseEv = () => {
    isCollapse.value = !isCollapse.value
    if (isCollapse.value == true) {
        leftWidth.value = '50px'
    } else {
        leftWidth.value = '180px'
    }
}
// 点击跳转
const menuClickEv = async (val) => {
    if (loginInfoStoreData.menuActive == val.router) {
        return
    }
    loginInfoStoreData.menuActive = val.router
    route.push({ path: val.router })

    // 判断是否增加顶部菜单导航
    tabsIsAdd(val, breadcrumbDataList)
}

// 点击导航菜单切换
const tabsItmEv = (val) => {
    console.log('点击导航菜单切换')
    console.log(val)
    if (loginInfoStoreData.menuActive == val.router) {
        return
    }
    loginInfoStoreData.menuActive = val.router
    route.push({ path: val.router })
    // 判断是否增加顶部菜单导航
    tabsIsAdd(val, breadcrumbDataList)
}

const tabsItmCloseEv = (val) => {
    console.log('点击导航菜单删除')
    console.log(val)

    // 删除菜单
    const activateTop = tabsIsDelete(val, breadcrumbDataList)
    console.log('activateTop',activateTop)
    // 设置激活菜单
    loginInfoStoreData.menuActive = activateTop.router

    // 切换路由
    route.push({ path: activateTop.router })
}

const updatePasswordShowEv = () => {
    dialogVisible.value = true
    passwordObj.value.oldPassword = ''
    passwordObj.value.noewPassword = ''
}
const updatePasswordEv = async () => {
    try {
        let arr_data = await UserLoginPut(passwordObj.value)
        if (arr_data.status != 200) {
            return
        }
        ElMessage.success('修改成功')
        dialogVisible.value = false
        await logOutEv()
    } catch (error) {
        ElMessage.error('修改接口请求失败' + error)
    }
}

</script>

<style lang='less' scoped>
.home {
    height: 100%;
    width: 100%;
    display: flex;
    overflow: hidden;
}

.left {
    width: var(--left-width);
    height: 100%;
    background-color: var(--menu-back-bround-color);
}

.right {
    width: calc(100% - var(--left-width));
    height: 100%;
    // background-color: green;
}



.right .top1 {
    height: calc(var(--right-top-height) - var(--crumbs-height));
    width: 100%;
    // background-color: yellowgreen;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 10px;
    padding-right: 20px;
    box-sizing: border-box;
    font-size: 14px;

    .top1-content {
        display: flex;
        align-items: center;
    }
}

.right .top2 {
    // width: 100%;
    // overflow-y: scroll;
    // padding-left: 10px;
    box-sizing: border-box;
    height: var(--crumbs-height);
    // line-height: var(--crumbs-height);
    display: flex;
    align-items: center;
    font-size: 12px;
    border-top: 0.5px rgba(220, 223, 230, 0.5) solid;
    border-bottom: 1px #dcdfe6 solid;
    box-sizing: border-box;
    // box-shadow: var(--el-box-shadow-light);
}

.right .top2 .top2-tabs {
    padding: 2px;
    box-sizing: border-box;
    height: 100%;

    .top2-tabs-itm {
        // width: 100%;
        height: 100%;
        min-width: 100px;
        padding-left: 10px;
        padding-right: 10px;
        box-sizing: border-box;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #d8dce5;
        cursor: pointer
    }

}

.right .top2 .top2-tabs:nth-of-type(1) {
    width: 70px;

    .top2-tabs-itm {
        min-width: 60px;
    }
}

.top2-tabs-activate {
    background-color: #42b983;
    color: #fff;
    border-color: #42b983;
    // border: 1px solid #42b983;
}


.right .bottom {
    height: calc(100% - var(--right-top-height));
    width: 100%;
    padding: 5px;
    box-sizing: border-box;
    // background-color: peachpuff;
}

.el-menu {
    border-right: 0px;
}

// 导航菜单背景颜色
:deep(.el-sub-menu .el-menu) {
    background-color: var(--menu-back-bround-color) !important;
}

// 菜单分组
:deep(.el-menu-item-group__title) {
    padding: 0;
}

// 展开颜色
:deep(.el-sub-menu .el-menu-item) {
    background-color: #1f2d3d !important;
}

// 张开鼠标移动上去颜色
:deep(.el-sub-menu .el-menu-item:hover) {
    // background-color: #001528 !important;
    background-color: #1E476B !important;
}

// 菜单不展开状态的宽度
.el-menu--collapse {
    width: 50px;
}

:deep(.el-breadcrumb__item:last-child .el-breadcrumb__inner) {
    color: #97a8be !important;
}

// 顶部导航tabs切换
.close-div {
    border-radius: 50%;
    width: 15px;
    height: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.close-div:hover {
    background-color: #97a8be;
    transition: background-color 0.5s ease-in-out;
}

// 退出登录样式
.popover-content {
    height: 30px;
    line-height: 30px;
    font-size: 15px;
    text-align: center;
}

.popover-content:nth-of-type(1) {
    border-bottom: 1px rgba(220, 223, 230, 0.5) solid;

}

.popover-content:hover {
    color: rgb(64, 158, 255);
    cursor: pointer;
}

// 修改密码弹窗
.close-itm {
    height: 40px;
}

// 禁止选中tabs页签中的文字
.no-select {
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
</style>